﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net.Mail;
using System.Net;
using System.Collections.Generic;
using YXShop.BLL.Admin;


namespace YXShop.Web.admin.order
{
    /// <summary>
    /// 银行支付
    /// </summary>
    public partial class order_bank_pay : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int id = ChangeHope.WebPage.PageRequest.GetQueryInt("OrderId");
                this.InitWebControl();
                this.BankBind();
                this.OrderInfoBind(this.GetOrderId(id));
                this.hlBackList.NavigateUrl = "order_order_info.aspx?OrderId=" + id + "";
            }
        }

        #region 验证
        private void InitWebControl()
        {
            ChangeHope.WebPage.WebControl.Validate(this.txtRemittanceMoney, "输入数字将作为汇款金额", "isint", "必填", "该项必须为数字类型");
            ChangeHope.WebPage.WebControl.Validate(this.txtPresentTick, "输入数字将作为赠送点券的点数", "isint", "必填", "该项必须为数字类型");
            ChangeHope.WebPage.WebControl.Validate(this.txtRemark, "输入相关的备注信息", "isnull", "必填", "该项不能为空");
            ChangeHope.WebPage.WebControl.Validate(this.txtBosomNote, "输入内部信息", "isnull", "必填", "该项不能为空");
            ChangeHope.WebPage.WebControl.SetDate(this.txtRemittanceDate);
            this.txtRemittanceDate.Text = DateTime.Now.ToShortDateString();
            this.Form.Attributes.Add("onsubmit", "return CheckForm()");
        }
        #endregion

        #region 初始化信息
        /// <summary>
        /// 银行数据
        /// </summary>
        protected void BankBind()
        {
            YXShop.BLL.SystemInfo.BankInfo bll = new YXShop.BLL.SystemInfo.BankInfo();
            List<YXShop.Model.SystemInfo.BankInfo> model = bll.GetAll();
            ddlBankName.DataSource = model;
            ddlBankName.DataTextField = "BankName";
            ddlBankName.DataValueField = "ID";
            ddlBankName.DataBind();
        }

        /// <summary>
        /// 订单信息初始化
        /// </summary>
        protected void OrderInfoBind(string orderId)
        {

            YXShop.BLL.Order.Orders bll = new YXShop.BLL.Order.Orders();
            YXShop.Model.Order.Orders model = bll.GetModel(orderId);
            if (model != null)
            {
                this.lblUserId.Text = model.ConsigneeName;
                this.lblUserName.Text = model.UserId;
                this.lblOrderId.Text = model.OrderId;
                this.lblMoneyPayed.Text = GetPayed(model.OrderId);//已付款
                this.lblMoneyCount.Text =Convert.ToDouble(model.FactPrice).ToString("f2");
                this.txtRemittanceMoney.Text =( Convert.ToDouble(model.FactPrice) - Convert.ToDouble(this.lblMoneyPayed.Text)).ToString();
                this.txtRemark.Text = model.Remark;   
            }
        }

        #endregion

        #region 公共方法
        /// <summary>
        /// 根据ID得到订单号
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        protected string GetOrderId(int id)
        {
            YXShop.BLL.Order.Orders bll = new YXShop.BLL.Order.Orders();
            YXShop.Model.Order.Orders model = bll.GetModel(id);
            if (model != null)
            {
                return model.OrderId;
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 计算已付款
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        protected string GetPayed(string orderId)
        {
            string totle = string.Empty;
            decimal remPrice =0;
            decimal payPrice = 0;
            decimal prePrice = 0;
            //银行支付
            YXShop.BLL.Order.RemittanceInfo remBll = new YXShop.BLL.Order.RemittanceInfo();
            List<YXShop.Model.Order.RemittanceInfo> remdate = remBll.GetAll("orderid='" + orderId + "'");
            if (remdate.Count > 0)
            {
                foreach (YXShop.Model.Order.RemittanceInfo da in remdate)
                {
                    remPrice += Convert.ToDecimal(da.RemittanceMoney.ToString());
                }
            }
            //现金支付
            YXShop.BLL.Order.PaymentMoney payBll = new YXShop.BLL.Order.PaymentMoney();
            List<YXShop.Model.Order.PaymentMoney> paydata = payBll.GetAll("orderid='" + orderId+"'");
            if (paydata.Count > 0)
            {
                foreach (YXShop.Model.Order.PaymentMoney da in paydata)
                {
                    payPrice += Convert.ToDecimal(da.GatheringMoney.ToString());
                }
            }
            //预付款
            YXShop.BLL.Order.PrepayMoney preBll = new YXShop.BLL.Order.PrepayMoney();
            List<YXShop.Model.Order.PrepayMoney> predata = preBll.GetAll("orderid='" + orderId + "'");
            if (predata.Count > 0)
            {
                foreach (YXShop.Model.Order.PrepayMoney da in predata)
                {
                    prePrice += Convert.ToDecimal(da.PayoutMoney);
                }
            }
            totle = (remPrice + payPrice + prePrice).ToString();
            return totle;
        }

        protected int GetUidByUserId(string userId)
        {
            YXShop.BLL.Member.MemberAccount bll = new YXShop.BLL.Member.MemberAccount();
            YXShop.Model.Member.MemberAccount model = bll.GetModel(userId);
            if (model != null)
            {
                return model.UID;
            }
            else
            {
                return 0;
            }
        }

        #region 邮件发送
        private void SendEmail(string toaddr, string titel, string body)
        {
            YXShop.BLL.SystemInfo.MailSetting mailBll = new YXShop.BLL.SystemInfo.MailSetting();
            YXShop.Model.SystemInfo.MailSetting mailModel = mailBll.GetModel();
            if (mailModel != null)
            {

                try
                {
                    MailMessage msg = new MailMessage();
                    //发送到
                    msg.To.Add(toaddr);
                    msg.From = new MailAddress(mailModel.MailId, titel, System.Text.Encoding.UTF8);
                    //标题
                    msg.Subject = titel;
                    msg.SubjectEncoding = System.Text.Encoding.UTF8;
                    //内容
                    msg.Body = body;
                    msg.BodyEncoding = System.Text.Encoding.UTF8;
                    msg.IsBodyHtml = true;
                    //优先级
                    msg.Priority = MailPriority.High;
                    SmtpClient client = new SmtpClient();
                    client.Credentials = new System.Net.NetworkCredential(mailModel.MailId, mailModel.MailPassword);
                    //Gmail邮箱发送  587
                    client.Port = 587;
                    client.Host = mailModel.SmtpServerIP;
                    client.EnableSsl = true;
                    client.Send(msg);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #endregion

        #region 短消息发送
        /// <summary>
        /// 发送短消息
        /// </summary>
        /// <param name="uid">用户自增ID</param>
        /// <param name="userid">用户账号</param>
        /// <param name="title">短消息标题</param>
        /// <param name="content">短消息内容</param>
        /// <param name="sender">发送人（管理员账号）</param>
        protected void SendMessage(int uid, string userid,string title, string content,string sender)
        {

            YXShop.BLL.Member.MailReceiver ReceBll = new YXShop.BLL.Member.MailReceiver();
            YXShop.Model.Member.MailReceiver ReceModel = new YXShop.Model.Member.MailReceiver();
            YXShop.BLL.Member.MemberAccount bll = new YXShop.BLL.Member.MemberAccount();
            if (!bll.Exists(userid))
            {
                this.ltlMsg.Text = "不存在用户：" + userid;
                this.pnlMsg.Visible = true;
                this.pnlMsg.CssClass = "actionErr";
                return;
            }
            ReceModel.ReceiverId = uid;
            ReceModel.Receiver = userid;
            ReceModel.ReceiveTime = DateTime.Now;
            ReceModel.Stat = 0;
            ReceModel.IsRead = 0;
            ReceModel.Title = title;
            ReceModel.Body = content;
            ReceModel.Sender = sender;
            ReceBll.Add(ReceModel);

        }
        #endregion

        private Dictionary<string, string> GetInforMode(CheckBoxList CbList)
        {
            string val = string.Empty;
            string txt = string.Empty;
            foreach (ListItem lItem in CbList.Items)
            {
                if (lItem.Selected)
                {
                    val += lItem.Value + ",";
                    txt += lItem.Text + ",";
                }
            }
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("val", val.TrimEnd(','));
            dic.Add("txt", val.TrimEnd(','));
            return dic;
        }
        #endregion

        #region 计算商品总价
        private double TotalPrice(string orderId)
        {
            YXShop.BLL.Order.OrderProduct bll = new YXShop.BLL.Order.OrderProduct();
            DataTable dt = bll.GetListOrderProduct(orderId);
            double totalPrice = 0;
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    totalPrice += Convert.ToDouble(dt.Rows[i]["ProPrice"].ToString()) * Convert.ToDouble(dt.Rows[i]["ProNum"].ToString());
                }
            }
            return totalPrice;
        }
        #endregion

        protected void lbtnSave_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(this.txtRemittanceMoney.Text.Trim()) <= 0)
            {
                this.ltlMsg.Text = "操作失败!汇款金额不能为零.";
                this.pnlMsg.Visible = true;
                this.pnlMsg.CssClass = "actionErr";
                return;
            }
            YXShop.Model.Admin.AdminInfo adminInfo = (YXShop.Model.Admin.AdminInfo)YXShop.Common.AdministrorManager.Get();

            #region 订单银行资金
            YXShop.Model.Order.RemittanceInfo remModel = new YXShop.Model.Order.RemittanceInfo();
            YXShop.BLL.Order.RemittanceInfo remBll = new YXShop.BLL.Order.RemittanceInfo();
            remModel.OrderId = this.lblOrderId.Text;
            remModel.UserName = this.lblUserName.Text;
            remModel.RemittanceDate = Convert.ToDateTime(this.txtRemittanceDate.Text);
            remModel.RemittanceMoney = Convert.ToDecimal(this.txtRemittanceMoney.Text);
            remModel.RemintanceBank = Convert.ToInt32(this.ddlBankName.SelectedValue);
            remModel.PresentTicket =  Convert.ToDecimal(this.txtPresentTick.Text.Trim()) ;
            remModel.Remark = this.lblUserName.Text.Trim() != "" ? this.txtRemark.Text : "(非会员)客户名称" + this.lblUserId.Text + ";" + this.txtRemark.Text;
            remModel.InformMode = GetInforMode(cbxInformMode)["txt"]; //通知方式
            remModel.NoteDate = DateTime.Now;
            remModel.NoteName = adminInfo.AdminName;
            #endregion

            #region 用户交易明细
            YXShop.Model.Member.UserinAndExp userModel = new YXShop.Model.Member.UserinAndExp();
            YXShop.BLL.Member.UserinAndExp userBll = new YXShop.BLL.Member.UserinAndExp();
            
            //资金的明细
            userModel.UID = this.GetUidByUserId(this.lblUserName.Text);
            userModel.AdsumMoneyDate = Convert.ToDateTime(this.txtRemittanceDate.Text);
            userModel.AdsumMoney = Convert.ToDecimal(this.txtRemittanceMoney.Text);
            userModel.PresentCoupons = Convert.ToDecimal(this.txtRemittanceMoney.Text.Trim()) ;
            userModel.RemitMode = 1;
            userModel.RemitBank = this.ddlBankName.SelectedItem.Text;
            userModel.Remark = this.lblUserName.Text.Trim() != "" ? this.txtRemark.Text : "(非会员)客户名称" + this.lblUserId.Text + ";" + this.txtRemark.Text; ;
            userModel.FormMode = GetInforMode(cbxInformMode)["txt"]; //通知方式
            userModel.BosomNote = this.txtBosomNote.Text;
            userModel.NoteDate = DateTime.Now;
            userModel.NoteName = adminInfo.AdminName;
            userModel.InComeandExpState = 1;
            userModel.State = 0;
            userModel.UserId = this.lblUserName.Text;
            #endregion

            #region 订单状态
            YXShop.BLL.Order.Orders orderBll = new YXShop.BLL.Order.Orders();
            YXShop.Model.Order.Orders orderModel = orderBll.GetModel(this.lblOrderId.Text);
            #endregion

            #region 消息通知
            YXShop.BLL.Member.MemberAccount memberBll = new YXShop.BLL.Member.MemberAccount();
            YXShop.Model.Member.MemberAccount memberModel = memberBll.GetModel(this.lblUserName.Text);

           
            if (memberModel != null)
            {
                foreach (ListItem item in cbxInformMode.Items)
                {
                    if (item.Selected)
                    {
                        switch (item.Value)
                        {
                            case "0"://短消息形式
                                SendMessage(memberModel.UID, memberModel.UserId, "系统通知", "银行资金确认", adminInfo.AdminName);
                                break;
                            case "1"://邮件
                                SendEmail(memberModel.Email, "系统通知", "银行资金确认");
                                break;
                        }
                    }
                }
            }
            #endregion

            #region 点卷赠送明细
            YXShop.Model.Member.UserInfoNote infoModel = new YXShop.Model.Member.UserInfoNote();
            YXShop.BLL.Member.UserInfoNote infoBll = new YXShop.BLL.Member.UserInfoNote();
            if (this.lblUserName.Text.Trim() != "")
            {
                infoModel.UserID = memberModel.UID;
                infoModel.TicketCount = Convert.ToDecimal(this.txtPresentTick.Text.Trim());
                infoModel.Causation = "银行支付赠送点卷";
                infoModel.BosomNote = this.txtBosomNote.Text;
                infoModel.NoteDate = DateTime.Now;
                infoModel.NoteName = adminInfo.AdminName;
                infoModel.NoteType = 0;
                infoModel.BuckleOrAdd = 0;
                infoModel.Username = this.lblUserName.Text;
            }
            #endregion
            try
            {
                //已付款+此次汇款的总和
                decimal payTotail = Convert.ToDecimal(this.GetPayed(this.lblOrderId.Text)) + Convert.ToDecimal(this.txtRemittanceMoney.Text.Trim());

                #region 如果有多余的钱 
                if (payTotail > Convert.ToDecimal(orderModel.FactPrice))
                {
                    ChangeHope.WebPage.BasePage.PageError("输入的金额大于了订单总额！", "order_bank_pay.aspx?OrderId="+orderModel.Id);
                    return;
                }
                #endregion
                remBll.Add(remModel);
                userBll.Add(userModel);

                #region 赠送点卷
                if (int.Parse(this.txtPresentTick.Text)>0&&this.lblUserName.Text.Trim()!="")
                {
                    infoBll.Add(infoModel);
                    if (memberModel != null)
                    {
                        memberBll.Amend(memberModel.UID, "Coupons", memberModel.Coupons + Convert.ToDecimal(this.txtPresentTick.Text.Trim()));
                    }
                }
                #endregion

                #region 操作付款状态 订单状态
                int OrderId = ChangeHope.WebPage.PageRequest.GetQueryInt("OrderId");
                if (payTotail >= Convert.ToDecimal(orderModel.FactPrice))
                {
                    if (OrderId > 0)
                    {
                        orderBll.Amend(OrderId, "OrderStatus", YXShop.Common.OrdersStatusEnum.OrderStatu.未结清.GetHashCode());
                        orderBll.Amend(OrderId, "PaymentStatus", YXShop.Common.OrdersStatusEnum.PaymentStatu.已经付清.GetHashCode());
                        orderBll.Amend(OrderId, "OgisticsStatus", YXShop.Common.OrdersStatusEnum.OgisticsStatus.配送中.GetHashCode());
                    }
                }
                else
                {
                    if (OrderId > 0)
                    {
                        orderBll.Amend(OrderId, "OrderStatus", YXShop.Common.OrdersStatusEnum.OrderStatu.未结清.GetHashCode());
                        orderBll.Amend(OrderId, "PaymentStatus", YXShop.Common.OrdersStatusEnum.PaymentStatu.未付清.GetHashCode());
                    }
                }
                #endregion
                ChangeHope.WebPage.BasePage.PageRight("已保存该信息.", "order_bank_pay.aspx?OrderId=" + orderModel.Id, "<li><a href='order_order_info.aspx?OrderId="+orderModel.Id.ToString()+"'>返回信息页</a></li>");
            }
            catch
            {
                this.ltlMsg.Text = "操作失败!";
                this.pnlMsg.Visible = true;
                this.pnlMsg.CssClass = "actionErr";
            }
            finally
            {
                adminInfo = null;
                remModel = null;
                remBll = null;
                userModel = null;
                userBll = null;
                orderBll = null;
                orderModel = null;
                GC.Collect();
            }
        }


    }
}
